package com_djm_2025_05_16;

/**
 * 实现二分查找
 *
 * @author dengjiangming
 * @version 1.0.0
 * @date 2025-05-16
 */
public class Demo2 {

    //给定一个有序整型数组, 实现二分查找
    //二分查找要求
    public static int binarySearch(int[] arr, int key) {
        int left = 0;
        int right = arr.length - 1;
        int mid = 0;
        while (left <= right) {
            mid = (left + right) / 2;
            if (arr[mid] == key) {
                //找到了，直接返回
                break;
            } else if (arr[mid] < key) {
                //arr[mid] < key，说明key在arr[mid]的右侧
                left = mid + 1;
            } else {
                //arr[mid] > key,说明key在arr[mid]的左侧
                right = mid - 1;
            }
        }

        //当left > right 时说明没有找到key，此时返回 -1

        if (left > right) {
            return -1;
        }

        return mid;
    }



    //测试二分查找
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8};
        int index = 0;
        index = binarySearch(arr, 1);
        System.out.println(arr[index]);
        index = binarySearch(arr, 2);
        System.out.println(arr[index]);
        index = binarySearch(arr, 3);
        System.out.println(arr[index]);
        index = binarySearch(arr, 4);
        System.out.println(arr[index]);
        index = binarySearch(arr, 5);
        System.out.println(arr[index]);
        index = binarySearch(arr, 6);
        System.out.println(arr[index]);
        index = binarySearch(arr, 7);
        System.out.println(arr[index]);
        index = binarySearch(arr, 8);
        System.out.println(arr[index]);

        index = binarySearch(arr, 10);
        System.out.println(index);
    }
}
